package 力扣.链表;

public class 反转链表II_92 {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null){
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p = dummy;
        int pos = 0;
        while (p != null){//找到left指针的前驱
            if (pos == left - 1){
                break;
            }
            p = p.next;
            pos++;
        }
        if (p != null){//判断left是否存在
            ListNode p2 = p;
            while (p2 != null){//找到right指针
                if (pos == right){
                    break;
                }
                p2 = p2.next;
                pos++;
            }
            if (p2 != null){//right是否存在
                ListNode rightlater = p2.next;//right节点的后继节点
                p2.next = null;
                //反转链表
                ListNode pre = null;
                ListNode t1 = p.next;
                while (t1 != null){
                    ListNode t2 = t1.next;
                    t1.next = pre;
                    pre = t1;
                    t1 = t2;
                }
                if (p.next != null){
                    p.next.next = rightlater;
                    p.next = pre;
                }
            }
        }
        return dummy.next;
    }
}
